<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useNaiveForm } from '@/hooks/common/form';
import { fetchAddPosition, fetchGetDeptTree, fetchUpdatePosition } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'PositionOperateModal'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Post | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.position.addPost'),
    edit: $t('page.manage.position.editPost')
  };
  return titles[props.operateType];
});

type Model = Pick<Api.SystemManage.Post, 'postId' | 'postName' | 'postCode' | 'deptId' | 'status'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    postId: '',
    postName: '',
    postCode: '',
    deptId: null,
    // 默认启用
    status: 1
  };
}

// 表单校验规则
const rules = {
  postName: [
    {
      required: true,
      message: $t('page.manage.position.form.postName'),
      trigger: ['input', 'blur']
    }
  ],
  postCode: [
    {
      required: true,
      message: $t('page.manage.position.form.postCode'),
      trigger: ['input', 'blur']
    }
  ]
};

/** the enabled dept tree options */
const deptTreeOptions = ref();

async function getDeptTreeOptions() {
  const { error, data } = await fetchGetDeptTree();

  if (!error) {
    deptTreeOptions.value = [...data];
  }
}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    // 确保正确映射所有字段，处理 null 值和默认值
    Object.assign(model, {
      postId: props.rowData.postId || '',
      postName: props.rowData.postName || '',
      postCode: props.rowData.postCode || '',
      deptId: props.rowData.deptId || null,
      status: props.rowData.status ?? 1 // 使用 ?? 确保 0 值不被覆盖
    });
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  try {
    let result;
    if (props.operateType === 'add') {
      result = await fetchAddPosition(model as Api.SystemManage.Post);
    } else {
      result = await fetchUpdatePosition(model as Api.SystemManage.Post);
    }

    if (!result.error) {
      const successMessage = props.operateType === 'add' ? $t('common.addSuccess') : $t('common.updateSuccess');
      window.$message?.success(successMessage);
      closeModal();
      emit('submitted');
    } else {
      window.$message?.error(result.error.message || $t('common.operationFailed'));
    }
  } catch (error) {
    window.$message?.error($t('common.operationFailed'));
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    getDeptTreeOptions();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" preset="dialog" :title="title" style="width: 1000px; max-width: 90vw">
    <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
      <NGrid :cols="2" :x-gap="16">
        <NFormItemGi :label="$t('page.manage.position.postId')" path="postId">
          <NInput v-model:value="model.postId" :placeholder="$t('page.manage.position.form.postId')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.position.postName')" path="postName">
          <NInput v-model:value="model.postName" :placeholder="$t('page.manage.position.form.postName')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.position.postCode')" path="postCode">
          <NInput v-model:value="model.postCode" :placeholder="$t('page.manage.position.form.postCode')" />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.position.belongDept')" path="deptId">
          <NTreeSelect
            v-model:value="model.deptId"
            :options="deptTreeOptions"
            :placeholder="$t('page.manage.position.form.belongDept')"
            clearable
            filterable
            show-path
            separator=" / "
            key-field="deptId"
            label-field="deptName"
            children-field="children"
          />
        </NFormItemGi>

        <NFormItemGi :label="$t('page.manage.position.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItemGi>
      </NGrid>
    </NForm>

    <template #action>
      <NSpace>
        <NButton @click="closeModal">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
